import 'package:duqing/components/song_card.dart';
import 'package:duqing/models/song_model.dart';
import 'package:duqing/services/song_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class SongPage extends StatefulWidget {
  const SongPage({Key key}) : super(key: key);

  @override
  _SongPageState createState() => _SongPageState();
}

class _SongPageState extends State<SongPage> with AutomaticKeepAliveClientMixin{
  List<SongItem> _songList = SongList(([])).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool err = false;
  String errorMessage;

  EasyRefreshController _easyRefreshController;

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
  }

  Future  _onLoad() async{
    _getSource(push: true);
    _easyRefreshController.finishLoad(noMore: !hasMore);
  }

  Future  _onRefresh() async{
    page = 1;
    _getSource(push: false);
    // _easyRefreshController.finishRefresh(noMore: !hasMore);
    _easyRefreshController.resetLoadState();
  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
  }

  Future _getSource({bool push = false}) async {
    try {
      Map<String, dynamic> result =
          await SongService.getSongs(page: page, limit: limit);
      SongList songListModel = SongList.fromJson(result['data']);

      setState(() {
        hasMore = page * limit < result['total'];
        page++;
        if (push) {
          _songList.addAll(songListModel.list);
        } else {
          _songList = songListModel.list;
        }
      });
    } catch (e, s) {
      err = true;
      errorMessage = e.toString();
      print(s);
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      firstRefresh: true,
      controller: _easyRefreshController,
      header: ClassicalHeader(),
      footer: ClassicalFooter(),
      onLoad: _onLoad,
      onRefresh: _onRefresh,
      child: ListView.builder(
        itemCount: _songList.length,
        itemBuilder: (BuildContext context, int index) {
          return Column(
            children: [
              const SizedBox(
                height: 8,
              ),
              SongCard(
                songItem: _songList[index],
              ),
            ],
          );
        },
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
